package com.atguigu.tingshu.order.strategy.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.atguigu.tingshu.album.client.AlbumInfoFeignClient;
import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.strategy.OrderTradeStrategy;
import com.atguigu.tingshu.vo.album.TrackPayVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
@Slf4j

//声音购买实现类
public class TrackOrderTradeStrategy implements OrderTradeStrategy {

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    @Autowired
    private AlbumInfoFeignClient albumInfoFeignClient;

    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Override
    public OrderInfoVo trade(TradeVo tradeVo) {

        //获取声音id
        Long trackId = tradeVo.getItemId();
        Integer trackCount = tradeVo.getTrackCount();   // 购买的集数
        if(trackCount < 0) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR) ;
        }

        // 根据声音的id查询声音数据
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(trackId);
        TrackInfo trackInfo = trackInfoResult.getData();

        //获取专辑的数据
        Long albumId = trackInfo.getAlbumId();
        Result<AlbumInfo> result = albumInfoFeignClient.getAlbumInfo(albumId);
        AlbumInfo albumInfo = result.getData();


        //构建orderInfoVo对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();


        // 构建相关金额数据, 声音购买不支持折扣
        BigDecimal price = albumInfo.getPrice();
        BigDecimal originalAmount = trackCount.intValue() > 0 ? price.multiply(new BigDecimal(trackCount)) : price ;
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(new BigDecimal("0.00"));
        orderInfoVo.setOrderAmount(originalAmount);
        
        
        // 构建订单明细，一个声音信息就是一个订单明细
        // 查询需要购买的声音的列表
        Result<List<TrackInfo>> trackInfoListResult = trackInfoFeignClient.findPaidTrackInfoList(trackId, trackCount);
        List<TrackInfo> trackInfos = trackInfoListResult.getData();

        List<OrderDetailVo> orderDetailVoList = trackInfos.stream().map(track -> {
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(track.getId());
            orderDetailVo.setItemName(track.getTrackTitle());
            orderDetailVo.setItemUrl(track.getCoverUrl());
            orderDetailVo.setItemPrice(albumInfo.getPrice());
            return orderDetailVo;
        }).collect(Collectors.toList());

        orderInfoVo.setOrderDetailVoList(orderDetailVoList);

        // 声音购买不支持折扣，因此没有减免明细数据
        orderInfoVo.setOrderDerateVoList(Lists.newArrayList());

        orderInfoVo.setTimestamp(SignHelper.getTimestamp());//当前系统时间
        Map<String, Object> map = JSON.parseObject(JSON.toJSONString(orderInfoVo), Map.class);
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);
        orderInfoVo.setItemType(tradeVo.getItemType());
        //创建一个UUID作为交易编号
        String tradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        orderInfoVo.setTradeNo(tradeNo);
        orderInfoVo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);

        String tradeNoRedisKey = RedisConstant.ORDER_TRADE_NO + tradeNo;
        redisTemplate.opsForValue().set(tradeNoRedisKey, tradeNo, 5, TimeUnit.MINUTES);


        return orderInfoVo;
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;
    }
}
